package com.java.computeronline.model.blo;

import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.java.computeronline.model.entity.Category;
import com.java.computeronline.model.entity.Manufacturer;

public class CategoryBLO {
	@SuppressWarnings("unchecked")
	public List<Category> list() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Category> categories = null;
		Query query = pm.newQuery(Category.class);
		categories = (List<Category>)query.execute();
		return categories;
	}

	public Category getById(Long id){
		Category category = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			category = pm.getObjectById(Category.class, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
		}
		return category;
	}

	
	public Category add(Category category) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(category);
        }catch(Exception ex){
        	ex.printStackTrace();
        } finally {
            pm.close();
        }
		return category;
	}
	
	public Category delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Category category;
		try {
			pm.currentTransaction().begin();
			category = pm.getObjectById(Category.class, id);
            pm.deletePersistent(category);
            pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return category;
	}
	public Category update(Category c){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Category category;
		try {
			pm.currentTransaction().begin();
			category = pm.getObjectById(Category.class, c.getId());
			category.setName(c.getName());
			category.setParentId(c.getParentId());
			category.setStatus(c.getStatus());
			category.setUrl(c.getUrl());
			pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return category;
	}
}
